import { getAlarmNameStatisticsApi } from '@/api/safeIndexApi';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { useRequest } from 'ahooks';
import { Select, Tooltip } from 'antd';
import dayjs from 'dayjs';
import * as echarts from 'echarts';
import type { FC } from 'react';
import { useEffect, useRef, useState } from 'react';
import Ostyle from './index.module.less';
const dateTypeOptions = [
  {
    label: '近一周',
    value: 6,
  },
  {
    label: '近一月',
    value: 29,
  },
];

const tipContent = '展示前十的驾驶行为（二级指标）的分类占比';

/**
 * @desc 驾驶行为二级占比 dxr 20231222
 */
export const CarBeSecPer: FC<any> = (props) => {
  const chartDom = useRef<HTMLDivElement>(null);
  const myChart = useRef<echarts.EChartsType>();
  const [queryTypeName, setQueryTypeName] = useState<string>(dateTypeOptions[0].label);
  const [params, setParams] = useState<any>({
    entId: props.entId,
    driverId: props.driverId,
    startTime: dayjs().subtract(6, 'days').format('YYYY-MM-DD'),
    endTime: dayjs().format('YYYY-MM-DD'),
  });
  useEffect(() => {
    if ((!myChart.current || myChart.current.isDisposed()) && chartDom.current) {
      myChart.current = echarts.init(chartDom.current);
      myChart.current.setOption({
        tooltip: {
          borderColor: '#fff',
          trigger: 'item',
          position: 'right',
          className: 'custom-tooltip-box',
          formatter: function (params: any) {
            const htmlText = `<div class='pie-tooltip-style'><div class="badgeT" style="background:${params.color}"></div><span>${params.name}</span><span>${params.value}%</span></div>`;
            return htmlText;
          },
        },
        legend: {
          bottom: '5%',
          left: 'center',
          selectedMode: false,
        },
        color: [
          '#66B8FF',
          '#8095FF',
          '#AA99FF',
          '#FF99E9',
          '#FF6666',
          '#FF8D66',
          '#FFC266',
          '#8ECC52',
          '#66CCAA',
          '#5CDAE6',
        ],
        series: [
          {
            type: 'pie',
            center: ['50%', '38%'],
            radius: ['60%', '30%'],
            avoidLabelOverlap: true,
            label: {
              show: false,
              // fontSize: 12,
              // position: "inside",
              // color: "#333333",
              // textBorderColor: "#fff",
              // textBorderWidth: 1,
              // formatter: "{d}%" //只要百分比
            },
            labelLine: { show: false },
            itemStyle: {
              // 控制弧的宽,
              borderColor: '#FFF',
            },
          },
        ],
      });
      return () => {
        if (myChart.current && !myChart.current.isDisposed()) {
          echarts.dispose(myChart.current);
        }
      };
    }
  }, []);
  const { run } = useRequest(
    async () => {
      return await getAlarmNameStatisticsApi(params);
    },
    {
      refreshDeps: [params],
      onSuccess(res: any) {
        if (res.code == '200') {
          let dataList = [];
          if (res.data.list.length > 0) {
            dataList = res.data.list.map((el: any) => {
              return {
                value: el.percent,
                name: el.alarmName,
              };
            });
          }

          myChart?.current?.setOption({
            series: [
              {
                data: dataList,
              },
            ],
          });
        }
      },
    },
  );
  return (
    <div className={Ostyle.drivebesecper_body}>
      <div className={Ostyle.cont_title}>
        驾驶行为二级占比
        <Tooltip placement="top" title={tipContent}>
          <QuestionCircleOutlined style={{ marginLeft: 5, color: '#999999' }} />
        </Tooltip>
        <Select<string>
          bordered={false}
          value={queryTypeName}
          onChange={(value, options: any) => {
            setQueryTypeName(options.label);
            if (!Array.isArray(options)) {
              // 计算开始结束时间
              params.startTime = dayjs().subtract(Number(value), 'days').format('YYYY-MM-DD');
              params.endTime = dayjs().format('YYYY-MM-DD');
              setParams(params);
              run();
            }
          }}
          options={dateTypeOptions}
          placement="bottomLeft"
          getPopupContainer={(target) => {
            if (chartDom.current) {
              return chartDom.current;
            } else {
              return target;
            }
          }}
        />
      </div>
      <div className={Ostyle.cont_cont}>
        <div className="flexr alc juc">
          <div ref={chartDom} className={Ostyle.cont_main}></div>
        </div>
      </div>
    </div>
  );
};
